<template>
  <div class="cus-add-docs-detail">
    <card style="margin: .2rem">
      <div class="van-hairline--bottom headTitle">
        <van-icon name="arrow-left" @click="back" />
        {{ title }}
      </div>
      <van-skeleton title :row="5" :loading="loading">
        <van-form ref="form" @submit="formSubmited">
          <van-field
            v-model="form.cusNumber"
            name="cusNumber"
            label="客户编号"
            placeholder="保存后自动生成客户编号"
            disabled
            v-show="pageType == 1"
          />

          <van-field
            readonly
            clickable
            name="cusCategory"
            :value="showForm.cusCategory_show"
            label="客户类别"
            placeholder="点击选择客户类别"
            :rules="[{required:true,message:'请选择客户类别',trigger:'onChange'}]"
            required
            :disabled="!canEdit"
            @click="canEdit?showCusCategoryPicker = true:false"
          />
          <van-popup v-model="showCusCategoryPicker" position="bottom">
            <van-picker
              show-toolbar
              :columns="cusCategoryArr"
              @confirm="onSelectConfirm($event,'cusCategory','showCusCategoryPicker')"
              @cancel="showCusCategoryPicker = false"
            />
          </van-popup>

          <van-field
            v-model="form.mnemonicCode"
            name="mnemonicCode"
            label="助记码"
            placeholder="请输入助记码"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.transType"
            name="transType"
            label="交易对象类型"
            placeholder="请输入交易对象类型"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.cusFullName"
            name="cusFullName"
            label="客户全名"
            placeholder="请输入客户全名"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.cusTaxCode"
            name="cusTaxCode"
            label="客户税籍编号"
            placeholder="请输入客户税籍编号"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.cusFullNameSec"
            name="cusFullNameSec"
            label="客户全名二"
            placeholder="请输入客户全名二"
            :disabled="!canEdit"
          />

          <van-field
            name="cusStatus"
            label="客户状态"
            required
            :rules="[{required:true,message:'请选择客户状态',trigger:'onChange'}]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group v-model="form.cusStatus" direction="horizontal" :disabled="!canEdit">
                <van-radio
                  :name="item.value"
                  v-for="item in cusStatusArr"
                  :key="item|getGuid"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="showForm.salesmanId_show"
            name="salesmanId"
            label="跟进业务员"
            placeholder="请选择跟进业务员"
            required
            readonly
            clickable
            :rules="[{ validator:salesmanValidate, message: '请输入正确内容' }]"
            :disabled="!canEdit"
            @click="canEdit?showSalesmanPopup = true:false"
          />
          <van-popup v-model="showSalesmanPopup" position="top" @opened="salesmanPopupOpened">
            <div class="salesmanPopupContainer">
              <van-search
                ref="salesmanSearchDom"
                v-model="salesmanSearchValue"
                placeholder="请输入搜索关键词"
                @input="salesmanInput"
              />
              <div class="salesmanItemContainer">
                <div
                  v-for="item in salesmanArr"
                  :key="item.id"
                  @click="salesmanItemClick(item)"
                  class="salesmanItem van-hairline--bottom"
                >{{ item.nickName }}</div>
              </div>
            </div>
          </van-popup>

          <van-field
            name="legalType"
            label="法人类型"
            required
            :rules="[{ required: true, message: '请选择法人类型' }]"
            :disabled="!canEdit"
          >
            <template #input>
              <van-radio-group v-model="form.legalType" direction="horizontal" :disabled="!canEdit">
                <van-radio
                  :name="item.value"
                  v-for="item in leagalTypeArr"
                  :key="item|getGuid"
                >{{ item.text }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field
            v-model="form.legalPerson"
            name="legalPerson"
            label="所属法人"
            placeholder="请输入所属法人"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.membership"
            name="membership"
            label="所属集团"
            placeholder="请输入所属集团"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.registCountry"
            name="registCountry"
            label="注册国家"
            placeholder="请输入注册国家"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.comRegistNumber"
            name="comRegistNumber"
            label="公司登记证号"
            placeholder="请输入公司登记证号"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.statisticCurrency"
            name="statisticCurrency"
            label="统计币种"
            placeholder="请输入统计币种"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.superAgent"
            name="superAgent"
            label="上级代理商"
            placeholder="请输入上级代理商"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.commissionAmount"
            name="commissionAmount"
            label="佣金总额"
            placeholder="请输入佣金总额"
            type="number"
            :disabled="!canEdit"
          />

          <van-field
            readonly
            clickable
            name="startBusinessDay"
            :value="form.startBusinessDay"
            label="创业日"
            placeholder="点击选择日期"
            :disabled="!canEdit"
            @click="canEdit ? startBusinessDayShow = true : false"
          />
          <van-calendar v-model="startBusinessDayShow" @confirm="startBusinessDayConfirm" />

          <van-field v-model="form.headMan" name="headMan" label="负责人" placeholder="负责人" />

          <van-field
            v-model="form.capital"
            name="capital"
            label="资本额"
            placeholder="请输入资本额"
            type="number"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.annualSale"
            name="annualSale"
            label="年营业额"
            placeholder="请输入年营业额"
            type="number"
            :disabled="!canEdit"
          />

          <van-field
            readonly
            clickable
            :value="form.empNumber"
            name="empNumber"
            label="员工人数"
            placeholder="请输入员工人数"
            :disabled="!canEdit"
            @touchstart.native.stop="canEdit ? empNumberShow = true : false"
          />
          <van-number-keyboard
            v-model="form.empNumber"
            :show="empNumberShow"
            close-button-text="完成"
            @blur="empNumberShow = false"
          />

          <van-field
            v-model="form.industry"
            name="industry"
            label="产业别"
            placeholder="请输入产业别"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.sizeClass"
            name="sizeClass"
            label="规模分类"
            placeholder="请输入规模分类"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.mainProduct"
            name="mainProduct"
            label="主要经营产品"
            placeholder="请输入主要经营产品"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.dataOrigin"
            name="dataOrigin"
            label="数据源"
            placeholder="请输入数据源"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.customsNumber"
            name="customsNumber"
            label="海关监管编号"
            placeholder="请输入海关监管编号"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.bondedBusiness"
            name="bondedBusiness"
            label="保税业务人员"
            placeholder="请输入保税业务人员"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.province"
            name="province"
            label="省份"
            placeholder="请输入省份"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.city"
            name="city"
            label="城市"
            placeholder="请输入城市"
            :disabled="!canEdit"
          />

          <van-field
            v-model="form.area"
            name="area"
            label="地区"
            placeholder="请输入地区"
            :disabled="!canEdit"
          />
        </van-form>
        <div style="margin: .3rem;">
          <van-row type="flex">
            <van-col class="bottomBtnCol" v-if="pageType == 1">
              <van-button
                round
                block
                type="default"
                native-type="button"
                @click="canEditBtnClick"
              >{{ canEdit?'取消':'编辑' }}</van-button>
            </van-col>
            <van-col class="bottomBtnCol">
              <van-button
                round
                block
                type="info"
                native-type="button"
                @click="okBtnClick"
                :disabled="!canEdit"
              >确定</van-button>
            </van-col>
          </van-row>
        </div>
      </van-skeleton>
    </card>
  </div>
</template>

<script>
import Card from "@/components/Card";
import {
  Form,
  Field,
  Picker,
  Calendar,
  RadioGroup,
  Radio,
  Popup,
  Button,
  Search,
  NumberKeyboard,
  Toast,
  Skeleton,
  Icon,
  Row,
  Col
} from "vant";
import {
  _cusCategoryDict,
  _cusStatusDict,
  _leagalTypeArrDict
} from "@/utils/dict";
import { formatDate } from "@/utils";
// import Popper from "vue-popperjs";
import "vue-popperjs/dist/vue-popper.css";
import { mapActions, mapMutations } from "vuex";
import Fuse from "fuse.js";
import Vue from "vue";
export default {
  components: {
    Card,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Search.name]: Search,
    [NumberKeyboard.name]: NumberKeyboard,
    [Skeleton.name]: Skeleton,
    [Icon.name]: Icon,
    [Row.name]: Row,
    [Col.name]: Col
    // popper: Popper
  },
  data() {
    return {
      title: "",
      loading: true,
      form: {
        cusNumber: "",
        cusCategory: "",
        mnemonicCode: "",
        transType: "",
        cusFullName: "",
        cusTaxCode: "",
        cusStatus: "1",
        salesmanId: "",
        legalType: "1",
        legalPerson: "",
        membership: "",
        registCountry: "",
        comRegistNumber: "",
        statisticCurrency: "",
        superAgent: "",
        commissionAmount: "",
        startBusinessDay: "",
        headMan: "",
        capital: "",
        annualSale: "",
        empNumber: "",
        industry: "",
        sizeClass: "",
        mainProduct: "",
        dataOrigin: "",
        customsNumber: "",
        bondedBusiness: "",
        province: "",
        city: "",
        area: ""
      },
      showForm: {
        cusCategory_show: "",
        salesmanId_show: ""
      },
      pageType: 0,
      cusCategoryArr: _cusCategoryDict,
      cusStatusArr: _cusStatusDict,
      leagalTypeArr: _leagalTypeArrDict,
      showCusCategoryPicker: false,
      showSalesmanPopup: false,
      commissionAmountShow: false,
      startBusinessDayShow: false,
      empNumberShow: false,
      salesmanSearchValue: "",
      salesmanArr: [],
      salesmanArrOrigin: [],
      canEdit: false
    };
  },
  created() {
    if (this.$route.query.type == "add") {
      this.title = "添加客户";
      document.title = "添加客户";
      this.pageType = 0;
      this.canEdit = true;
    } else {
      this.title = "编辑客户";
      document.title = "编辑客户";
      this.pageType = 1;
    }
  },
  mounted() {
    this.initData();
  },
  beforeDestroy() {
    this.resetDocsDetail();
  },
  methods: {
    ...mapMutations({
      resetDocsDetail: "cusAddDocs/resetDocsDetail"
    }),
    ...mapActions({
      querySalesman: "cusAddDocs/querySalesman",
      addCustomer: "cusAddDocs/addCustomer",
      updateCustomer: "cusAddDocs/updateCustomer"
    }),
    initData() {
      this.querySalesman({})
        .then(res => {
          this.salesmanArr = res.data;
          if (res.data.length) {
            this.salesmanArrOrigin = JSON.parse(JSON.stringify(res.data));
          }
          if (this.pageType == 1) {
            let detail = this.$store.state.cusAddDocs.docsDetail;
            console.log(detail);
            detail.startBusinessDay = formatDate(
              new Date(detail.startBusinessDay),
              "yyyy-MM-dd"
            );

            for (const key in detail) {
              if (detail.hasOwnProperty(key)) {
                const element = detail[key];
                this.form[key] = "" + element;
              }
            }
            let cusCategoryDict = Vue.filter("cusCategoryDict");
            this.showForm.cusCategory_show = cusCategoryDict(
              detail.cusCategory
            );
            for (let i = 0, len = res.data.length; i < len; i++) {
              if (res.data[i].id == detail.salesmanId) {
                this.showForm.salesmanId_show = res.data[i].nickName;
                break;
              }
            }
          }
          this.loading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    salesmanValidate(val) {
      return this.form.salesmanId ? true : false;
    },
    salesmanPopupOpened() {
      let child = this.$refs.salesmanSearchDom.getElementsByTagName("input");
      child[0].focus();
    },
    salesmanItemClick(item) {
      console.log(item);
      this.form.salesmanId = item.id;
      this.showForm.salesmanId_show = item.nickName;
      this.showSalesmanPopup = false;
    },
    salesmanInput(value) {
      if (value == "") {
        this.salesmanArr = JSON.parse(JSON.stringify(this.salesmanArrOrigin));
      } else {
        const options = {
          includeScore: true,
          // Search in `author` and in `tags` array
          keys: ["nickName"]
        };
        const fuse = new Fuse(this.salesmanArrOrigin, options);
        const result = fuse.search(value);
        this.salesmanArr = [];
        result.forEach(e => {
          this.salesmanArr.push(e.item);
        });
      }
    },
    onSelectConfirm(value, key, visible) {
      console.log(value, key);
      this.form[key] = value.value;
      this.showForm[`${key}_show`] = value.text;
      this[visible] = false;
    },
    startBusinessDayConfirm(date) {
      console.log(date);
      this.form.startBusinessDay = formatDate(date, "yyyy-MM-dd");
      this.startBusinessDayShow = false;
    },
    back() {
      this.$router.go(-1);
    },
    canEditBtnClick() {
      if (this.canEdit) {
        let detail = this.$store.state.cusAddDocs.docsDetail;
        console.log(detail);
        this.form = {
          cusNumber: "",
          cusCategory: "",
          mnemonicCode: "",
          transType: "",
          cusFullName: "",
          cusTaxCode: "",
          cusStatus: "1",
          salesmanId: "",
          legalType: "1",
          legalPerson: "",
          membership: "",
          registCountry: "",
          comRegistNumber: "",
          statisticCurrency: "",
          superAgent: "",
          commissionAmount: "",
          startBusinessDay: "",
          headMan: "",
          capital: "",
          annualSale: "",
          empNumber: "",
          industry: "",
          sizeClass: "",
          mainProduct: "",
          dataOrigin: "",
          customsNumber: "",
          bondedBusiness: "",
          province: "",
          city: "",
          area: ""
        };
        detail.startBusinessDay = formatDate(
          new Date(detail.startBusinessDay),
          "yyyy-MM-dd"
        );

        for (const key in detail) {
          if (detail.hasOwnProperty(key)) {
            const element = detail[key];
            this.form[key] = "" + element;
          }
        }
        let cusCategoryDict = Vue.filter("cusCategoryDict");
        this.showForm.cusCategory_show = cusCategoryDict(detail.cusCategory);
        for (let i = 0, len = this.salesmanArrOrigin.length; i < len; i++) {
          if (this.salesmanArrOrigin[i].id == detail.salesmanId) {
            this.showForm.salesmanId_show = this.salesmanArrOrigin[i].nickName;
            break;
          }
        }
      }
      this.canEdit = !this.canEdit;
    },
    okBtnClick() {
      this.$refs.form.submit();
    },
    formSubmited() {
      console.log("submit", this.form);

      if (this.pageType == 0) {
        // 添加
        this.addCustomer(this.form)
          .then(res => {
            console.log(res);
            if (res.success) {
              Toast.success("新建成功");
              this.$router.go(-1);
            } else {
              Toast.fail(`新建失败：${res.message}`);
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else if (this.pageType == 1) {
        // 更新
        this.updateCustomer(this.form)
          .then(res => {
            console.log(res);
            if (res.success) {
              Toast.success("更新成功");
              // this.$router.go(-1);
            } else {
              Toast.fail(`更新失败：${res.message}`);
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.cus-add-docs-detail {
  background-image: linear-gradient(rgb(216, 231, 240), white);
  padding: 8px;
  .headTitle {
    font-size: 24px;
    padding-bottom: 12px;
    align-items: center;
    display: flex;
  }
  .van-radio {
    margin-bottom: 8px;
  }
  .salesmanPopupContainer {
    max-height: 100vh;
    overflow: hidden;
    .salesmanItemContainer {
      overflow: auto;
      position: relative;
      max-height: 600px;
      .salesmanItem {
        padding: 8px 12px;
      }
    }
  }
  .bottomBtnCol {
    flex: 1;
    padding: 8px;
  }
}
</style>